package a66weding.com.jiehuntong.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.home.BaseHomeActivity;
import a66weding.com.jiehuntong.adapter.GuestAdaputer;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.GuestBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.ShareInviteBean;
import a66weding.com.jiehuntong.beans.SimpleBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.FileUtil;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * 宾客统计
 */
public class GuestsActivity extends BaseHomeActivity implements View.OnClickListener, OnNetResultListener,GuestAdaputer.RemoveCallBack {

    private TextView tv_count_person;
    private ListView gust_listview;
    private XRefreshView guests_xrefreshview;
    int mPage=1;
    private List<GuestBean.DataBean> mGuestList = new ArrayList<>();
    private GuestAdaputer guestAdaputer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guests);
        initView();
        initDate();
    }

    private void initDate() {
        int uId = DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();
        HttpRequestBean httpRequestBean = new HttpRequestBean();
        httpRequestBean.setUrl(RequestCode.SURL + RequestCode.GETGUESTS + uId + "&pageIndex=" + mPage + "&pagesize=5");
        httpRequestBean.setClazz(GuestBean.class);
        httpRequestBean.setRequestMethod(RequestCode.GETREQUEST);
        httpRequestBean.setListener(this);
        httpRequestBean.setRequestCode(RequestCode.IMAGESTORYORDER);
        HttpHandleUtil.executeCommonGet(this, httpRequestBean);
    }

    private void initView() {
        tv_count_person = (TextView) findViewById(R.id.tv_count_person);
        tv_count_person.setOnClickListener(this);
        gust_listview = (ListView) findViewById(R.id.gust_listview);
        guestAdaputer = new GuestAdaputer(GuestsActivity.this, mGuestList, this);
        gust_listview.setAdapter(guestAdaputer);
        guests_xrefreshview = (XRefreshView) findViewById(R.id.guests_xrefreshview);
        guests_xrefreshview.setOnClickListener(this);
        //是否允许下拉刷新
        guests_xrefreshview.setPullRefreshEnable(true);
        // 设置是否可以上拉加载
        guests_xrefreshview.setPullLoadEnable(false);
        // 设置刷新完成以后，headerview固定的时间
        guests_xrefreshview.setPinnedTime(1000);

        guests_xrefreshview.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onLoadMore(boolean isSlience) {
                initDate();
            }
            @Override
            public void onRefresh() {
                super.onRefresh();
                mPage = 1;//刷新的时候第1页是最新数据
                initDate();
            }
        });
        //头部导航
        TextView tv_tools_dayplan_backcontent = (TextView) findViewById(R.id.tv_tools_dayplan_backcontent);
        LinearLayout llay_toolsheader_back = (LinearLayout) findViewById(R.id.llay_toolsheader_back);
        TextView tv_tools_dayplan_title = (TextView) findViewById(R.id.tv_tools_dayplan_title);
        TextView tv_tools_dayplan_addtype1 = (TextView) findViewById(R.id.tv_tools_dayplan_addtype1);
        ImageView img_tools_dayplan_backcontent = (ImageView) findViewById(R.id.img_tools_dayplan_backcontent);
        img_tools_dayplan_backcontent.setOnClickListener(this);
        tv_tools_dayplan_backcontent.setText("     ");
        tv_tools_dayplan_title.setText("宾客统计");
        tv_tools_dayplan_addtype1.setText("分享");
        tv_tools_dayplan_addtype1.setVisibility(View.VISIBLE);
        tv_tools_dayplan_backcontent.setOnClickListener(this);
        llay_toolsheader_back.setOnClickListener(this);
        tv_tools_dayplan_backcontent.setOnClickListener(this);
        tv_tools_dayplan_addtype1.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llay_toolsheader_back:
                finish();
                break;
            case R.id.img_tools_dayplan_backcontent:
                finish();
                break;
            case R.id.tv_tools_dayplan_backcontent:
                finish();
                break;
            case R.id.tv_tools_dayplan_addtype1:
                showShare();
                break;
        }
    }

    /**
     * 一键分享
     */
    private void showShare() {
        String title = "",url = "",description = "";
        ShareInviteBean.DataBean picData = null;
        ShareInviteBean shareInviteBean = (ShareInviteBean) getIntent().getSerializableExtra("shareInviteBean");
        if(shareInviteBean != null){
            url = shareInviteBean.getDomain();//点开后网址链接地址
            title = shareInviteBean.getName();
            description = shareInviteBean.getContent();
            picData = shareInviteBean.getData();
            if(picData == null || TextUtils.isEmpty(picData.getNvc_Pic())){
                copyToSD(this);//这个拷贝 的是应用图标在下边用到了
            }
        }
        if (shareInviteBean == null || TextUtils.isEmpty(title)|| TextUtils.isEmpty(shareInviteBean.getDomain())) {
            CUtils.showToast("请您完善新人信息");
            return;
        }
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        oks.setTitle(title);
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl(url);
        // text是分享文本，所有平台都需要这个字段
        oks.setText(description);

        if (picData != null && !TextUtils.isEmpty(picData.getNvc_Pic())) {
            oks.setImageUrl(picData.getNvc_Pic());
        } else {
            // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
            oks.setImagePath("/sdcard/invitation66.jpg");//确保SDcard下面存在此张图片
        }
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(url);
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment(description);
        oks.setSiteUrl(url);
        // 启动分享GUI
        oks.show(this);
    }

    /**
     * 把raw的图片存到SD卡上
     */
    public static void copyToSD(Context context) {
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            File dbFile = FileUtil.getDefaultFile("invitation66.jpg");
            if (!dbFile.exists()) {
                is = context.getResources().openRawResource(
                        R.raw.share_invitation);
                fos = new FileOutputStream(dbFile);

                byte[] buffer = new byte[8 * 1024];// 8K
                while (is.read(buffer) > 0)// >
                {
                    fos.write(buffer);
                }
            }
        } catch (Exception e) {

        } finally {
            try {
                if (is != null) {
                    is.close();
                }

                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if (data instanceof GuestBean) {
            GuestBean response = (GuestBean) data;
            if (response != null && response.getResCode() != null) {
                if (response.getResCode().equals("0000")) {
                    tv_count_person.setText("共" + response.getCount() + "人参加");//设置总人数
                    setDate2ListView(response);
                } else {
                    CUtils.showToast(response.getMsg());
                }
            }
        } else if (data instanceof SimpleBean) {
            SimpleBean spb = (SimpleBean) data;
            if (spb != null && spb.getResCode() != null) {
                if (spb.getResCode().equals("0000")) {
                    CUtils.showToast("删除" + spb.getMsg());
                    if (guestIndex > -1) {
                        guestAdaputer.remove(guestIndex);
                        guestAdaputer.notifyDataSetChanged();
                        guestIndex = -1;//重置
                    }
                   //请柬内容有修改后调用该行代码通知界面刷新
                    sendBroadcast(new Intent(ElectronicInvitationActivity.ACTION_REFRESH_INVITATION));
                } else {
                    CUtils.showToast(spb.getMsg());
                }
            }
        }
    }

    //设置数据到listview展示
    private void setDate2ListView(GuestBean response) {
        mGuestList = response.getData();//请求回来的数据
        if (mPage ==1) {//第一次进入和,刷新都是地第0页面
            //上拉刷新与第一次刷新
            guestAdaputer.clear();//清空list中数据
            guestAdaputer.append(mGuestList);
            guests_xrefreshview.stopRefresh();//停止刷新
            //当本次有数据的时候当前页数才+1
        } else {
            //下拉加载更多
            guests_xrefreshview.stopLoadMore();//停止加载更多
            guestAdaputer.append(mGuestList);
            if (mGuestList.size() < 1) {
                CUtils.showToast("数据已全部加载完毕了");
            }
        }
        Log.i("1212", "setDate2ListView: "+mGuestList.size());
        if (mGuestList != null && mGuestList.size() > 0) {
            mPage++;
        }

        if (mPage>0){
            // 设置是否可以上拉加载
            guests_xrefreshview.setPullLoadEnable(true);
        }
    }

    @Override
    public void onError(ErrorBean errorBean) {
        guests_xrefreshview.stopLoadMore();//停止加载更多
        guests_xrefreshview.stopRefresh();//停止刷新
        CUtils.showToast("数据请求失败");
    }

    int guestIndex = -1;//这个是移除宾客的下标,如果是-1列表不可能存在,则不移除

    //删除来宾接口回调
    @Override
    public void removeGuest(GuestBean.DataBean bean, int position) {
        guestIndex = position;
        HttpRequestBean httpRequestBean = new HttpRequestBean();
        httpRequestBean.setUrl(RequestCode.SURL + RequestCode.DELETEGUEST + bean.getI_Id());
        httpRequestBean.setClazz(SimpleBean.class);
        httpRequestBean.setRequestMethod(RequestCode.POSTEQUEST);
        httpRequestBean.setListener(this);
        HttpHandleUtil.executeCommonGet(this, httpRequestBean);
    }
}
